import {AxdrType} from "../asn1.axdr/AxdrType";
import {ReverseByteArrayInputStream} from "../ReverseByteArrayInputStream";
import {ReverseByteArrayOutputStream} from "../ReverseByteArrayOutputStream";
import {Buffer} from "buffer";
import {OAD} from "./OAD";
import {AxdrEnum} from "../asn1.axdr/AxdrEnum";
import {Get_Result} from "./Get_Result";


export class ProxySetThenGet implements AxdrType{

    dataCode : Buffer | null = null;
    soad : OAD | null = null;
    dar : AxdrEnum | null = null;
    road : OAD | null = null;
    getResult : Get_Result | null = null;

    constructor() {
    }

    set_dataCode(dataCode : Buffer){
        this.dataCode = dataCode;
    }

    set_all(soad : OAD, dar : AxdrEnum, road : OAD, getResult : Get_Result){
        this.soad = soad;
        this.dar = dar;
        this.road = road;
        this.getResult = getResult;
    }

    decode(input: ReverseByteArrayInputStream): number {
        let codeLength = 0;

        this.soad = new OAD();
        codeLength += this.soad.decode(input);

        this.dar = new AxdrEnum();
        this.dar.set_const();
        codeLength += this.dar.decode(input);

        this.road = new OAD();
        codeLength += this.road.decode(input);

        this.getResult = new Get_Result();
        codeLength += this.getResult.decode(input);

        return codeLength;
    }

    encode(output: ReverseByteArrayOutputStream): number {
        let codeLength;

        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (let i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if(this.getResult != null && this.road != null && this.dar != null && this.soad != null){
                codeLength = 0;
                codeLength += this.getResult.encode(output);
                codeLength += this.road.encode(output);
                codeLength += this.dar.encode(output);
                codeLength += this.soad.encode(output);
            }else{
                throw new Error("getResult || road || dar || soad is null");
            }
        }
        return codeLength;
    }

    encodeAndSave(encodingSizeGuess: number) {
        let revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    toString(): string {
        if (this.soad != null && this.dar != null && this.road != null && this.getResult != null) {
            return "sequence: {"+ "soad: " + this.soad + ", dar: " + this.dar + ", road: " + this.road + ", getresult: " + this.getResult  + "}";
        } else {
            return "getResult || road || dar || soad is null";
        }
    }

}
